from django.http import HttpResponse
from django.shortcuts import get_object_or_404, redirect, render
from django.contrib.admin.views.decorators import staff_member_required

from .forms import ImageUploadForm
from .models import Image


@staff_member_required
def list(request):
    """
    用户图片列表
    """
    image_list = Image.objects.filter(user=request.user)
    return render(request, 'images/list.html', {
        'image_list':image_list
    })


@staff_member_required
def delete(request, id):
    """
    删除图片
    """
    image = get_object_or_404(Image, pk=id)
    image.delete()
    return redirect('images:list')


@staff_member_required
def view(request, id):
    """
    查看图片
    """
    image = get_object_or_404(Image, pk=id)
    return render(request, 'images/view.html', {
        'image': image,
    })


@staff_member_required
def upload(request):
    """
    上传图片
    """
    if request.method == 'POST':
        form = ImageUploadForm(data=request.POST, files=request.FILES)
        if form.is_valid():
            image = form.save(commit=False)
            image.user = request.user
            image.save()
            return redirect(image)
    else:
        form = ImageUploadForm()
    return render(request, 'images/upload.html', {
        'form': form,
    })
